import 'package:hive/hive.dart';
import 'package:uuid/uuid.dart';
import '../models/share_post_model.dart';
import '../models/user_model.dart';
import 'user_service.dart';
import 'share_comment_service.dart';

class ShareService {
  final Box<SharePostModel> _shareBox = Hive.box<SharePostModel>('shares');
  final Uuid _uuid = Uuid();

  // 创建分享
  Future<SharePostModel> createSharePost({
    required String userId,
    required String description,
    required List<String> imageUrls,
    List<String> viewerIds = const [],
  }) async {
    final share = SharePostModel(
      id: _uuid.v4(),
      userId: userId,
      description: description,
      imageUrls: imageUrls,
      createdAt: DateTime.now(),
      viewerIds: viewerIds,
    );

    await _shareBox.put(share.id, share);
    return share;
  }

  // 获取分享
  SharePostModel? getShareById(String id) {
    return _shareBox.get(id);
  }

  // 更新分享
  Future<void> updateSharePost(SharePostModel share) async {
    await _shareBox.put(share.id, share);
  }

  // 删除分享
  Future<void> deleteSharePost(String id) async {
    await _shareBox.delete(id);
  }

  // 获取所有分享
  List<SharePostModel> getAllShares() {
    return _shareBox.values.toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt)); // 按创建时间降序排序
  }

  // 获取用户的分享
  List<SharePostModel> getUserShares(String userId) {
    return _shareBox.values.where((share) => share.userId == userId).toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  // 切换收藏状态
  Future<void> toggleCollected(String id, bool isCollected) async {
    final share = getShareById(id);
    if (share != null) {
      share.isCollected = isCollected;
      await updateSharePost(share);
    }
  }

  // 添加查看者
  Future<void> addViewer(String shareId, String userId) async {
    final share = getShareById(shareId);
    if (share != null) {
      share.addViewer(userId);
      await updateSharePost(share);
    }
  }

  // 搜索分享
  List<SharePostModel> searchShares(String query) {
    query = query.toLowerCase();
    return _shareBox.values
        .where((share) => share.description.toLowerCase().contains(query))
        .toList()
      ..sort((a, b) => b.createdAt.compareTo(a.createdAt));
  }

  // 添加样例分享数据（开发测试用）
  Future<void> addSampleShares() async {
    if (_shareBox.isEmpty) {
      // 获取用户列表
      final userBox = Hive.box<UserModel>('users');
      final users = userBox.values.toList();

      // 找到用户名为"lalala"的用户（Ezra）
      UserModel? ezraUser;
      try {
        ezraUser = users.firstWhere((user) => user.username == 'lalala');
      } catch (e) {
        // 如果找不到，则使用第一个用户
        if (users.isNotEmpty) {
          ezraUser = users[0];
        }
      }

      // 确保有足够的用户
      if (users.length >= 3 && ezraUser != null) {
        // 获取除Ezra外的所有用户ID用于浏览记录
        final otherUsers = users.where((u) => u.id != ezraUser!.id).toList();

        // 为每个分享创建随机的浏览者列表
        List<String> getRandomViewers(List<UserModel> viewerPool, int count) {
          // 确保不要超过可用用户数量
          count = count > viewerPool.length ? viewerPool.length : count;

          // 随机选择用户作为浏览者
          viewerPool.shuffle();
          return viewerPool.take(count).map((u) => u.id).toList();
        }

        final commentService = ShareCommentService();

        // 第一条 Ezra 的分享 - 添加4-6个浏览者
        final share1 = await createSharePost(
          userId: ezraUser.id, // Ezra用户
          description:
              'Diving into the deep blue is like entering another world. Every breath brings people closer to the heartbeat of nature.',
          imageUrls: [
            'assets/images/share1.png',
            'assets/images/share2.png',
            'assets/images/share3.png',
          ],
          viewerIds: getRandomViewers(
            otherUsers,
            4 + (DateTime.now().millisecondsSinceEpoch % 3),
          ), // 4-6个浏览者
        );
        // 默认英文评论
        if (otherUsers.isNotEmpty) {
          await commentService.addComment(
            shareId: share1.id,
            userId: otherUsers[0].id,
            content: 'So beautiful! Take me with you next time!',
          );
        }
        if (otherUsers.length > 1) {
          await commentService.addComment(
            shareId: share1.id,
            userId: otherUsers[1].id,
            content: 'The ocean world is really amazing!',
          );
        }
        if (otherUsers.length > 2) {
          await commentService.addComment(
            shareId: share1.id,
            userId: otherUsers[2].id,
            content: 'I love the blue color, it is so peaceful.',
          );
        }

        // 第二条 Ezra 的分享 - 添加3-5个浏览者
        final share2 = await createSharePost(
          userId: ezraUser.id, // Ezra用户
          description:
              'The underwater world is quiet and mysterious. The colorful coral clusters and the leisurely swimming turtles are the hidden blue paradise.',
          imageUrls: [
            'assets/images/share4.png',
            'assets/images/share5.png',
            'assets/images/share6.png',
          ],
          viewerIds: getRandomViewers(
            otherUsers,
            3 + (DateTime.now().millisecondsSinceEpoch % 3),
          ), // 3-5个浏览者
        );
        if (otherUsers.isNotEmpty) {
          await commentService.addComment(
            shareId: share2.id,
            userId: otherUsers[0].id,
            content: 'The colors are so rich, I\'m jealous!',
          );
        }
        if (otherUsers.length > 1) {
          await commentService.addComment(
            shareId: share2.id,
            userId: otherUsers[1].id,
            content: 'I want to see turtles too!',
          );
        }
        if (otherUsers.length > 2) {
          await commentService.addComment(
            shareId: share2.id,
            userId: otherUsers[2].id,
            content: 'This is a real paradise under the sea.',
          );
        }

        // 其他用户的分享
        final otherViewers = users.where((u) => true).toList(); // 所有用户都可以作为浏览者池
        if (otherUsers.length >= 3) {
          // 第三个用户的分享 - 添加2-4个浏览者
          final share3 = await createSharePost(
            userId: otherUsers[0].id,
            description:
                'At the bottom of the sea, time seems to be still, but beauty is swimming, and the silent wonders are around.',
            imageUrls: [
              'assets/images/share7.png',
              'assets/images/share8.png',
              'assets/images/share9.png',
            ],
            viewerIds: getRandomViewers(
              otherViewers,
              2 + (DateTime.now().millisecondsSinceEpoch % 3),
            ), // 2-4个浏览者
          );
          if (users.length > 1) {
            await commentService.addComment(
              shareId: share3.id,
              userId: users[1].id,
              content: 'The underwater world is so quiet, I love it.',
            );
          }
          if (users.length > 2) {
            await commentService.addComment(
              shareId: share3.id,
              userId: users[2].id,
              content: 'Amazing photo! The sea is full of wonders.',
            );
          }

          // 第四个用户的分享 - 添加1-3个浏览者
          final share4 = await createSharePost(
            userId: otherUsers[1].id,
            description:
                'What the sea taught me is a deeper calm. Only by diving into the deep blue can you see its true appearance.',
            imageUrls: [
              'assets/images/share10.png',
              'assets/images/share11.png',
              'assets/images/share12.png',
            ],
            viewerIds: getRandomViewers(
              otherViewers,
              1 + (DateTime.now().millisecondsSinceEpoch % 3),
            ), // 1-3个浏览者
          );
          if (users.length > 0) {
            await commentService.addComment(
              shareId: share4.id,
              userId: users[0].id,
              content: 'Diving really brings peace to my mind.',
            );
          }
          if (users.length > 2) {
            await commentService.addComment(
              shareId: share4.id,
              userId: users[2].id,
              content: 'The deep blue is so attractive!',
            );
          }

          // 第五个用户的分享 - 添加2-3个浏览者
          final share5 = await createSharePost(
            userId: otherUsers[2].id,
            description:
                'The first time I held my breath and dived underwater, I had a brief exchange with a group of small fish. It turns out that the bottom of the sea is really so beautiful!',
            imageUrls: [
              'assets/images/share13.png',
              'assets/images/share14.png',
              'assets/images/share15.png',
            ],
            viewerIds: getRandomViewers(
              otherViewers,
              2 + (DateTime.now().millisecondsSinceEpoch % 2),
            ), // 2-3个浏览者
          );
          if (users.length > 0) {
            await commentService.addComment(
              shareId: share5.id,
              userId: users[0].id,
              content: 'I want to try diving too!',
            );
          }
          if (users.length > 1) {
            await commentService.addComment(
              shareId: share5.id,
              userId: users[1].id,
              content: 'The fish are so cute!',
            );
          }
          if (users.length > 2) {
            await commentService.addComment(
              shareId: share5.id,
              userId: users[2].id,
              content: 'The underwater world is full of surprises.',
            );
          }

          if (otherUsers.length > 3) {
            // 第六个用户的分享 - 添加1-2个浏览者
            final share6 = await createSharePost(
              userId: otherUsers[3].id,
              description:
                  'From the surface to the bottom of the sea, the first breath underwater is always novel and unforgettable, and I feel a kind of freedom I have never had before!',
              imageUrls: [
                'assets/images/share16.png',
                'assets/images/share17.png',
                'assets/images/share18.png',
              ],
              viewerIds: getRandomViewers(
                otherViewers,
                1 + (DateTime.now().millisecondsSinceEpoch % 2),
              ), // 1-2个浏览者
            );
            if (users.length > 0) {
              await commentService.addComment(
                shareId: share6.id,
                userId: users[0].id,
                content: 'This looks so cool! I want to try it too!',
              );
            }
            if (users.length > 1) {
              await commentService.addComment(
                shareId: share6.id,
                userId: users[1].id,
                content: 'The feeling of freedom underwater is amazing.',
              );
            }
            if (users.length > 2) {
              await commentService.addComment(
                shareId: share6.id,
                userId: users[2].id,
                content: 'Unforgettable experience! The sea is so beautiful.',
              );
            }
          }
        }
      }
    }
  }
}
